"use client";

import * as React from "react";
import { useMemoizedFn, useScroll } from "ahooks";
import { ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";

interface BackToTopProps {
  scrollRef?: React.RefObject<HTMLDivElement | null>;
}

export const BackToTop = ({ scrollRef }: BackToTopProps) => {
  const scroll = useScroll(() => scrollRef?.current ?? document);

  const handleClick = useMemoizedFn(() => {
    if (scrollRef?.current) {
      scrollRef.current.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    document.documentElement.scrollTo({ top: 0, behavior: "smooth" });
  });

  return (
    <div
      className={cn(
        "fixed right-8 bottom-8 border border-gray-500 rounded-full p-2 cursor-pointer hover:bg-gray-50",
        {
          hidden: (scroll?.top ?? 0) < 100,
        }
      )}
      onClick={handleClick}
    >
      <ChevronUp className="size-4 text-gray-500 " />
    </div>
  );
};
